package com.auz.datagenerator.connector.heuristiclink;

/**
 * Class used to parse the equation provided in the heuristic link
 * @author Aurelien Bonnel
 */
public class Parser {

	private Lexer lexer;

	/**
	 * Constructor
	 * @param _equation - the equation to parse
	 */
	public Parser(String _equation) {
		lexer = new Lexer(_equation);
	}

	/**
	 * Parses the overall expression and returns the result of the equation
	 * @return the result of the equation
	 */
	public double parseExpression() {
		double result = parseMulExp();
		while(true) {
			if(lexer.nextToken() == '+') {
				lexer.read();
				result += parseMulExp();
			} else if(lexer.nextToken() == '-') {
				lexer.read();
				result -= parseMulExp();
			} else
				return result;
		}
	}

	/**
	 * Parses a multiplicating or dividing expression and returns the quotient or product
	 * @return the quotient or product of the expression
	 */
	private double parseMulExp() {
		double result = parseRootExp();
		while (true) {
			if (lexer.nextToken() == '*') {
				lexer.read();
				result *= parseRootExp();
			} else if (lexer.nextToken() == '/') {
				lexer.read();
				result /= parseRootExp();
			} else 
				return result;
		}
	}

	/**
	 * Parses a root expression and returns the result 
	 * @return the result of the expression
	 */
	private double parseRootExp() {
		double result = 0.0;
		if (lexer.nextToken() == '(') {
			lexer.read();
			result = parseExpression();
			lexer.read();
		} else if (lexer.nextToken() == Lexer.NUMBER_TOKEN){
			result = lexer.getNum();
			lexer.read();
		}
		return result;
	}

}
